//
//  XLComposePictureViw.swift
//  XLVeibo
//
//  Created by macbook on 16/7/3.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit

let composeImageCllId = "pictureID"

class XLComposePictureViw: UICollectionView {

    //告诉外界弹出相册
    var composePictureViewClosure:(()->())?
    
    //保存图片的数组
    var imageList:[UIImage] = [UIImage]()
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //供外界调用
    func addImage(image:UIImage){
        
        //往数组中添加，每次都是第一个
        imageList.insert(image, atIndex: 0)
        
        //如果大于九删除第一个
        if imageList.count > 9 {
            
            imageList.removeLast()
        }
        
        //刷新
        reloadData()
    }
    
    
    func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        delegate = self
        dataSource = self
        //注册cell
        registerClass(XLComposePictureViewCell.self, forCellWithReuseIdentifier: composeImageCllId)
       
        //设置layout
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let marginWith:CGFloat = 5
        let itemWH = (KScreenW - 20 - 2 * marginWith) / 3
        
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        
        //设置水平，垂直间距
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        
        //一开始隐藏collection
        self.hidden = true
        
        
    }
}

extension XLComposePictureViw:UICollectionViewDelegate,UICollectionViewDataSource{
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = imageList.count
        
        if count == 0 || count == 9 {
            
            return count
        }else{
        
            return imageList.count + 1
            
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(composeImageCllId, forIndexPath: indexPath) as! XLComposePictureViewCell
        
        if imageList.count == indexPath.item {
 
             cell.image = nil
            
        }else{
        
            cell.image = imageList[indexPath.item]
            
            //显示collectionView
            self.hidden = false
          }
        
        
        //实现闭包的删除功能
        cell.deleteButClouse = {
        
        //删除数组元素
            self.imageList.removeAtIndex(indexPath.item)
            
            //如果count == 0 当删除完图片后影藏ColletionView
            if self.imageList.count == 0 {
                
                self.hidden = true
            }
            //刷新UI
            self.reloadData()

        }
        
        

       
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if imageList.count == indexPath.item {
            
            print("加号按钮")
            composePictureViewClosure?()
        }
    }
}


//自定义cell 
class XLComposePictureViewCell:UICollectionViewCell{

  //声明一个删除按钮的闭包
    var deleteButClouse:(()->())?
    
    //恭外界赋值
    var image:UIImage?{
    
        didSet{
        
            //设置加号按钮
            if image == nil {
              
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
             // MARK: - 影藏加号的删除按钮
                deleteBtn.hidden = true
            }else{
            
                //正常显示
                bgImageView.image = image
                //解决cell重用问题
                bgImageView.highlightedImage = nil
                
                //因为cell的重用问题，显示删除按钮
                deleteBtn.hidden = false
             }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI(){
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteBtn)
        //添加约束
        bgImageView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        //删除图片按钮
        deleteBtn.snp_makeConstraints { (make) in
            
            make.top.right.equalTo(contentView)
        }
        
    }
    
    // MARK: -  懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    private lazy var deleteBtn:UIButton = {
    
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        //添加点击方法
        btn.addTarget(self, action: #selector(XLComposePictureViewCell.deleteBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    
    }()
    
    
    // MARK: - 删除按钮的实现
    
    func deleteBtnClick(){
    
        deleteButClouse?()
      
    }
}












